import React, { FC, useState } from "react"
import { Typography, Empty, Table, Tag, Button, Space, Modal, message, Spin } from "antd"
import styles from "./common.module.scss"
import { useRequest, useTitle } from "ahooks"
import { ExclamationCircleOutlined } from "@ant-design/icons"
import ListSearch from "../../components/ListSearch"
import useLoadQuestionListData from "../../hooks/useLoadQuestionListData"
import ListPage from "../../components/ListPage"
import { deleteQuestionService, updateQuestionService } from "../../services/question"

const Trash: FC = () => {
    const { Title } = Typography

    const { confirm } = Modal

    // 修改标题（使用第三方hook）
    useTitle("问卷星途 - 回收站")

    const { loading, data = {}, refresh } = useLoadQuestionListData({ isDeleted: true })
    const { list = [], total } = data

    // 记录选中的 id
    const [selectedIds, setSelectedIds] = useState<string[]>([])

    // 恢复删除的问卷（修改属性）
    const { run: recover } = useRequest(
        async () => {
            // 选中才能恢复（选中多项）
            for await (const id of selectedIds) {
                await updateQuestionService(id, { isDeleted: false })
            }
        },
        {
            manual: true,
            debounceWait: 500, // 防抖
            onSuccess() {
                message.success("恢复成功")
                refresh() // 手动刷新列表
                // 清空ids列表
                setSelectedIds([])
            }
        }
    )

    // 彻底删除
    const { run: deleteQuestion } = useRequest(async () => await deleteQuestionService(selectedIds), {
        manual: true,
        onSuccess() {
            message.success("删除成功")
            refresh() // 手动刷新列表
            // 清空ids列表
            setSelectedIds([])
        }
    })

    function del() {
        confirm({
            title: "是否确定彻底删除？",
            icon: <ExclamationCircleOutlined />,
            content: "删除后不可以恢复",
            okText: "确定",
            cancelText: "取消",
            onOk: deleteQuestion
        })
    }

    // 定义表格的列
    const tableColumns = [
        {
            title: "标题",
            dataIndex: "title"
            // 循环列的key，他会默认去dataIndex的值
        },
        {
            title: "是否发布",
            dataIndex: "isPublished",
            // 根据数据源返回自定义的js片段
            render: (isPublished: boolean) => {
                return isPublished ? <Tag color="processing">已发布</Tag> : <Tag>未发布</Tag>
            }
        },
        {
            title: "答卷",
            dataIndex: "answerCount"
        },
        {
            title: "创建时间",
            dataIndex: "createdAt"
        }
    ]

    const TableElem = (
        <>
            <div style={{ marginBottom: "16px", textAlign: "right" }}>
                <Space>
                    <Button type="primary" disabled={selectedIds.length === 0} onClick={recover}>
                        恢复
                    </Button>
                    <Button type="primary" disabled={selectedIds.length === 0} danger onClick={del}>
                        彻底删除
                    </Button>
                </Space>
            </div>
            <Table
                dataSource={list}
                columns={tableColumns}
                pagination={false}
                rowKey={(q: any) => q._id}
                rowSelection={{
                    type: "checkbox",
                    onChange: selectedRowKeys => {
                        // console.log("selectedRowKeys", selectedRowKeys)
                        // 记录选中的值(类型断言)
                        setSelectedIds(selectedRowKeys as string[])
                    }
                }}
            />
        </>
    )

    return (
        <>
            <div className={styles.header}>
                <div className={styles.left}>
                    {/* title渲染为h1 */}
                    <Title level={3}>回收站</Title>
                </div>
                <div className={styles.right}>
                    <ListSearch />
                </div>
            </div>
            <div className={styles.content}>
                {/* 加载中显示加载的符号 */}
                {loading && (
                    <div style={{ textAlign: "center" }}>
                        <Spin />
                    </div>
                )}
                {/* 不是加载状态就显示列表 */}
                {!loading && list.length === 0 && <Empty description="暂无数据" />}
                {/* 不使用它提供的分页 */}
                {list.length > 0 && TableElem}
                {/* rowkey是告诉table 使用什么作为key */}
            </div>
            <div className={styles.footer}>
                <ListPage total={total} />
            </div>
        </>
    )
}

export default Trash
